package com.tzstcl.framework.runner;

import com.alibaba.fastjson.JSONArray;
import com.tzstcl.framework.redis.RedisService;
import com.tzstcl.sys.user.model.SysDict;
import com.tzstcl.sys.user.service.impl.SysDictServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 公司：天筑科技股份有限公司
 * 作者：zgq
 * 日期：2018年09月25日
 * 说明：系统启动时—数据字典初始化
 */
@Order(1)
@Component
public class DataDictInit implements ApplicationRunner {
    private final static Logger LOGGER = LogManager.getLogger(DataDictInit.class);

    @Autowired
    SysDictServiceImpl sysDictService;
    @Autowired
    RedisService redisService;

    @Override
    public void run(ApplicationArguments args) {
        LOGGER.info("初始化数据字典开始");
        try {
            initDataDict();

        } catch (Exception e) {
            LOGGER.error("初始化数据字典异常、异常信息:{}", e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("初始化数据字典结束");
    }

    /**
     * 初始化数据字典
     */
    public void initDataDict() {
        List<SysDict> sysDictList = sysDictService.selectListByCache(null);

        //组织数据字典为 map方式
        Map<String, List<Object>> dataDictMap = new HashMap<>();
        for (SysDict dict : sysDictList) {
            dict.setPageNum(null);
            dict.setPageSize(null);
            if (dataDictMap.containsKey(dict.getDictType())) {
                if (null != dataDictMap.get(dict.getDictType())) {
                    dataDictMap.get(dict.getDictType()).add(dict);
                } else {
                    List<Object> dicts = new ArrayList<>();
                    dicts.add(dict);
                    dataDictMap.put(dict.getDictType(), dicts);
                }
            } else {
                List<Object> dicts = new ArrayList<>();
                dicts.add(dict);
                dataDictMap.put(dict.getDictType(), dicts);
            }
        }

        Set<String> keySet = dataDictMap.keySet();
        for (String key : keySet) {
            redisService.set(key, new JSONArray(dataDictMap.get(key)).toJSONString());
        }
    }

    /**
     * 获取数据字典值
     */
    public String getDataDictByType(String key) {
        Object res = redisService.get(key);
        if (null != res) {
            return (String) res;
        } else {
            return "[]";
        }

    }
}
